/*
 * @Author: shiguo
 * @Date: 2022-04-24 13:56:47
 * @LastEditors: shiguo
 * @LastEditTime: 2022-09-09 10:59:38
 * @FilePath: /@aks-dev/easyui/lib/TextInputArea/TextInputArea.tsx
 */
import React from 'react'
import { View, Text, TextInput, StyleSheet } from 'react-native'
import {px2dp} from '../../screen/px2dp'
import {px2sp} from '../../screen/px2sp'


import type { TextInputAreaProps } from '.'

export default React.forwardRef<TextInputAreaProps.RefAttributes, Partial<TextInputAreaProps>>((props, ref) => {
    const { defaultValue, placeholder, maxLength = 200, on, ...rest } = props

    const [value, setValue] = React.useState<string | undefined>(defaultValue)

    React.useLayoutEffect(() => {
        setValue(defaultValue)
    }, [defaultValue])


    React.useImperativeHandle<unknown,TextInputAreaProps.RefAttributes>(ref, () => ({
        value: value,
    }), [value])

    return (
        <View style={[styles.container, rest.style]}>


            <TextInput
                {...rest}
                style={[styles.textInput,rest.textInputStyle]}
                value={value}
                onChangeText={txt => {
                    setValue(txt);
                    on && on(txt);
                }}
                multiline={true}
                textAlignVertical={'top'}
                maxLength={maxLength}
                placeholder={placeholder}

            />

            <View style={styles.corner}>
                <Text style={styles.limit}>
                    <Text style={{ ...styles.limit, color: value && value?.length > (maxLength - 5) ? 'red' : '#AFAFAF' }}>{value?.length || 0}</Text>
                    /
                    {maxLength}
                </Text>
            </View>
        </View>
    )
})



const styles = StyleSheet.create({
    container: {
        // backgroundColor: '#F5F5F5',
        minHeight: px2dp(200),
        // borderRadius: px2dp(10),
        backgroundColor:'white'
    },
    textInput: {
        flex: 1,
        margin: px2dp(15),
        marginBottom: px2dp(8),
        fontSize:px2sp(14)
        // backgroundColor: 'red'
    },
    corner: {
        // position: 'absolute',
        // backgroundColor:'cyan',
        marginHorizontal: px2dp(15),
        marginBottom: px2dp(8)
    },
    limit: {
        textAlign: 'right',
        fontSize: px2sp(10),
        color: '#AFAFAF'
    },


})